<template>
    <div>
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px">
            <div v-show="showForm == 2">
                <div class="container">
                    <h3 style="margin-bottom: 20px">产品信息</h3>
                    <el-form-item label="产品类型：">
                        {{ruleForm.materialType}}
                    </el-form-item>
                    <el-row class="demo-ruleForm">
                        <el-col :span="12">
                            <el-form-item label="品名：">
                                {{ruleForm.breedName}}
                            </el-form-item>
                            <el-form-item label="规格码：">
                                {{ruleForm.specsCode}}
                            </el-form-item>
                            <el-form-item label="保质期：">
                                {{ruleForm.deadLine}}月
                            </el-form-item>
                            <el-form-item label="生产批号：">
                                {{ruleForm.batch}}
                            </el-form-item>
                            <el-form-item label="产品大类：">
                                {{ruleForm.inventoryType}}
                            </el-form-item>

                        </el-col>
                        <el-col :span="12">

                            <el-form-item>
                                &nbsp;&nbsp;
                            </el-form-item>
                            <el-form-item label="存货代码：">
                                {{ruleForm.inventoryCode}}
                            </el-form-item>
                            <el-form-item label="装量：">
                                {{ruleForm.pelletWeight}}g
                            </el-form-item>
                            <el-form-item label="生产负责人：">
                                {{ruleForm.principalUser}}
                            </el-form-item>
                        </el-col>
                    </el-row>
                </div>
                <div class="container" style="margin-top:20px">
                    <h3 style="margin-bottom: 20px">投料信息</h3>
                    <el-form-item label="投料：">
                        <el-col :span="3">
                            <el-form-item >
                                {{ruleForm.productName}}
                            </el-form-item>
                        </el-col>
                        <el-col :span="5">
                            <el-form-item label="生产批号：">
                                {{ruleForm.productBatch}}
                            </el-form-item>
                        </el-col>
                        <el-col :span="4" prop="scUseNum">
                            <el-form-item label="投入量：">
                                {{ruleForm.scUseNum}} {{ruleForm.scUseNumUnits}}
                            </el-form-item>
                        </el-col>
                        <el-col :span="4" >
                            <el-form-item label="质量标准：">
                                {{ruleForm.qualityStandard}}
                            </el-form-item>
                            <!-- <el-input v-model="ruleForm.qualityStandard"  disabled placeholder=""  style="width:220px"></el-input> -->
                            <!-- {{ruleForm.qualityStandard}} -->
                        </el-col>
                    </el-form-item>
                </div>
                <el-form-item class="footerFixed">
                    <el-button type="primary" @click="submitForm()">确认无误</el-button>
                    <el-button @click="backEdit">返回修改</el-button>
                </el-form-item>
            </div>
            <div v-show="showForm == 1">
                <div class="container">
                    <h3 style="margin-bottom: 20px">产品信息</h3>
                    <el-form-item  rm-item label="产品类型：" prop="materialType">
                        <el-radio-group v-model="ruleForm.materialType" @change="changeMaterType">
                            <el-radio label="中药饮片" border>中药饮片</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-row class="demo-ruleForm">
                        <el-col  :span='12'>
                            <el-form-item label="品名：" prop="breedName">
                                <el-select v-model="ruleForm.breedName" :remote-method="remoteMethod" @focus.native= "clear" :disabled="allDisabled" @change="changeBreed" remote value-key="id" filterable placeholder="请选择" style="width: auto;">
                                    <el-option
                                        v-for="item in breedList"
                                        :key="item.id"
                                        :label="item.breedName"
                                        :value="item"
                                    >
                                        {{ item.breedName }}
                                    </el-option>
                                </el-select>
                                <el-button style="margin-left:10px" @click="wuliaoLink">物料管理</el-button>
                            </el-form-item>
                        </el-col>
                        <el-col :span='12'>
                            <el-form-item label="规格码：" >
                                <el-select v-model="ruleForm.specsCode" :disabled="allDisabled"   remote value-key="breedName" filterable placeholder="请选择" style="width: auto;">
                                    <el-option
                                        v-for="item in codelist"
                                        :key="item"
                                        :label="item"
                                        :value="item"
                                    >
                                        {{ item }}
                                    </el-option>
                                </el-select>

                            </el-form-item>
                        </el-col>

                        <el-col :span='12'>
                            <el-form-item label="装量：">
                                {{ruleForm.pelletWeight}}g
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="存货代码：" prop="inventoryCode">
                                <el-select v-model="ruleForm.inventoryCode" :disabled="allDisabled" value-key="id" @change="changeInvent" filterable placeholder="请选择" style="width: auto;">
                                    <el-option
                                        :key="inventList.id"
                                        :label="inventList.inventoryCode"
                                        :value="inventList"
                                    >
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>

                        <el-col :span="24">
                            <el-form-item label="保质期：">
                                <el-input v-model.trim="deadLine" :disabled="disabled" style="width: 215px"></el-input>
                                <span style="margin-left:20px;">月</span>
                            </el-form-item>
                            <el-form-item label="产品大类：" prop="inventoryType">
                                <el-select v-model="ruleForm.inventoryType" placeholder="请选择" style="width: 200px;">
                                    <el-option v-for='item in categoryList' :key='item' :label='item' :value='item'></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="产品批号：" prop="batch">
                                <el-input v-model.trim="ruleForm.batch" :disabled="allDisabled" @change="changeBatch" style="width: 215px"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span = "12">
                            <el-form-item label="生产负责人：" prop="principalUser">
                                <el-select v-model="ruleForm.principalUser" filterable placeholder="请选择" value-key="id" @change="changePrincipa" style="width: auto">
                                    <el-option
                                        v-for="item in userList"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item"
                                    >
                                        {{item.name}}
                                    </el-option>
                                </el-select>
                                <el-button style="margin-left:10px" @click="staffsLink">员工管理</el-button>
                            </el-form-item>
                            <el-form-item label="生产日期：">
                                <el-input v-model="ruleForm.time" disabled style="width: 215px"></el-input>

                            </el-form-item>
                        </el-col>
                    </el-row>
                </div>
                <div class="container" style="margin-top:20px">
                    <h3 style="margin-bottom: 20px">投料品信息</h3>
                    <el-form-item>
                        <div style="width:250px;display:inline-block;">名称</div>
                        <div style="width:240px;display:inline-block;">生产批号</div>
                        <div style="width:240px;display:inline-block;">投入量</div>
                        <div style="width:240px;display:inline-block;">质量标准</div>
                    </el-form-item>
                    <el-form-item label="投料" required>
                        <el-col :span="4">
                            <el-form-item prop="productName" >
                                <el-select v-model="ruleForm.productName" :remote-method="remoteMethod1" remote :disabled="allDisabled" filterable @change="changePin" placeholder="名称" style="width:220px">
                                    <el-option
                                        v-for="item in productList"
                                        :key="item"
                                        :label="item"
                                        :value="item"
                                    >
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                            <el-form-item prop="productName">
                                <el-select v-model="manufactureBatch" filterable value-key="id" :disabled="isDisabled" placeholder="生产批号" @change="changeInBatch" style="width:220px">
                                    <el-option
                                        v-for="item in inBatchs"
                                        :key="item.id"
                                        :label="item.batch"
                                        :value="item"
                                    >
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="4" prop="scUseNum">
                            <el-input v-model.number="ruleForm.scUseNum" type="number" placeholder="投入量" @blur="changeNum" style="width:220px"></el-input>
                            {{ruleForm.scUseNumUnits}}
                        </el-col>
                        <el-col :span="4" >
                            <el-input v-model="ruleForm.qualityStandard"  disabled placeholder=""  style="width:220px"></el-input>
                            <!-- {{ruleForm.scUseNumUnits}} -->
                        </el-col>
                    </el-form-item>
                </div>
                <div style='height: 40px'></div>
                <el-form-item class="footerFixed">
                    <el-button type="primary" @click="submitRules('ruleForm')">提交</el-button>
                    <el-button @click="backPage">返回</el-button>
                </el-form-item>
            </div>
        </el-form>
    </div>
</template>
<script>
import {findQualityStandard,getspecscode,pack_findPackBreedName,pack_findMaterialBreedMsg,user_findAll,unit_findByList,warehouse_findAll,pack_save,pack_findById,pack_update,pack_existBatch,warehouse_findBreedName,warehouse_findBatchByBreedName,findBreedNameBySearch} from "@/request/api";
export default {
    data() {
        return {
            standardl:'',
            codelist:[],
            disabled:false,
            deadLine:'',
            time:'',
            showForm: 1,
            inventLists:[],
            inventList: [],
            breedList: [],
            materialType: '',
            userList: [],
            unitList: [],
            warehouseList: [],
            scUseNum: '',
            inBatchs: [],
            isDisabled: true,
            allDisabled: false,
            productList: [],
            manufactureBatch: '',
            inventoryCode: '',
            categoryList:[],
            ruleForm: {
                specsCode:'',
                materialType: '中药饮片',
                principalUser: '',
                principalUserId: '',
                inventoryCode: '',
                inventoryType:'',
                batch: '',
                totalNumber: '',
                // units: '袋',
                warehouseId: '',
                warehouse: '',
                dispenserCode: '',
                loadingUnits:'',
                loadingQuantity:'',
                breedName: '',
                scUseNum: '',
                surplusNum: '',
                productBatch:'',
            },
            rules:{
                materialType: [
                    { required: true, message: '不能为空', trigger: 'change' }
                ],
                breedName: [
                    { required: true, message: '不能为空', trigger: 'change' },
                ],
                inventoryCode: [
                    { required: true, message: '不能为空', trigger: 'change' }
                ],
                batch: [
                    { required: true, message: '不能为空', trigger: 'blur' },
                ],
                totalNumber: [
                    { required: true, message: '不能为空', trigger: 'blur' },
                ],
                principalUser: [
                    { required: true, message: '不能为空', trigger: 'change' }
                ],
                productName:[
                    { required: true, message: '不能为空', trigger: 'change' }
                ],
                scUseNum: [
                    { required: true, message: '不能为空', trigger: 'blur' },
                ],
                standard: [
                    { required: true, message: '不能为空', trigger: 'blur' },
                ],
            },
            materialTypeStor: '',
            newScUserNum: '',
            name:''
            // sceneUrls: [],
            // productUrls: [],
        }
    },
    mounted(){
        this.id = this.$route.query.id
        if(this.id == undefined){
            this.$store.commit('removeRuform','')
            this.init()
        }else{
            this.allDisabled = true
            this.init1()
            this.disabled = true
        }
        this.gettech()
    },
    methods: {
        gettech(){
            pack_findPackBreedName({
                materialType: '中药饮片',
                upperCase:"",
                ypCodeStandard:this.ruleForm.standard
            }).then((res)=>{
                this.breedList = res.data
            })
        },
        getInvestmentList(){
            warehouse_findBreedName({
                types: ['生产'],
                materialTypes: ['中药饮片(半成品)'],
                standard:this.ruleForm.standard
            }).then((res) =>{
                this.productList = res.data
            })
        },
        backEdit(){
            this.showForm = 1
            var date = new Date();
            var seperator1 = "-";
            var year = date.getFullYear();
            var month = date.getMonth() + 1;
            var strDate = date.getDate();
            if (month >= 1 && month <= 9) {
                month = "0" + month;
            }
            if (strDate >= 0 && strDate <= 9) {
                strDate = "0" + strDate;
            }
            var currentdate = year + seperator1 + month + seperator1 + strDate;
            var arr1 = currentdate.split("-")
            var arr2 = this.ruleForm.deadLine.split("-")
            var m1 =  Number(arr2[0]) - Number(arr1[0])
            var m2 = Number(arr2[1]) - Number(arr1[1])
            this.ruleForm.deadLine = m1*12 + m2
        },
        clear(){
            // this.ruleForm.breedName = ""
        },
        remoteMethod(query){
            pack_findPackBreedName({
                materialType: '中药饮片(半成品)',
                upperCase:query,
                ypCodeStandard:this.ruleForm.standard
            }).then((res)=>{
                this.breedList = res.data
            })

        },
        backPage () {
            this.$router.go(-1);
        },
        init(){

            // 用户列表
            user_findAll('').then((res)=>{
                this.userList = res.data
            })
            // 单位
            unit_findByList('').then((res) =>{
                this.unitList = res.data
            })
            // 仓库
            warehouse_findAll('').then((res) =>{
                this.warehouseList = res.data
            })

        },
        init1(){
            pack_findById(this.id).then((res) =>{
                this.ruleForm = Object.assign({},res.data);
                this.ruleForm.productName = res.data.manufacture.breedName
                this.manufactureBatch = res.data.manufacture.batch
                this.deadLine = res.data.deadLine
                this.ruleForm.pelletWeight = res.data.materialBreed.pelletWeight
                this.newScUserNum = res.data.scUseNum
                this.ruleForm.productBatch = res.data.manufacture.batch
                if(this.ruleForm.standard == "1"){
                    this.ruleForm.standardl = "国标"
                }
                if(this.ruleForm.standard == "2"){
                    this.ruleForm.standardl = "省标"
                }
                if(this.ruleForm.standard == "3"){
                    this.ruleForm.standardl = "省标-北京"
                }
                if(this.ruleForm.standard == "4"){
                    this.ruleForm.standardl = "省标-上海"
                }

            })
            this.init();
        },
        // 选择物料类型
        changeMaterType(val){},
        // 选择品名
        changeBreed(ele){
            this.ruleForm.breedId = ''
            this.ruleForm.loadingQuantity = ''
            this.ruleForm.pelletWeight = ''
            this.ruleForm.dispenserCode = ''
            this.ruleForm.ypQuantity = ''
            this.ruleForm.ypUnits = ''
            this.deadLine = ""
            this.ruleForm.inventoryCode = ''
            this.ruleForm.inventoryType = ''
            this.ruleForm.breedName = ele.breedName
            this.ruleForm.upperCase = ele.upperCase
            pack_findMaterialBreedMsg({
                breedName:ele.breedName,
                materialType: '中药饮片',
                standard:this.ruleForm.standard
            }).then((res) =>{
                this.inventList = res.data[0]
                this.ruleForm.pelletWeight = this.inventList.pelletWeight
                this.inventLists.push({
                    label:this.inventList.inventoryCode,
                    id:this.inventList.id,
                    value:this.inventList
                })
                this.categoryList = res.data.map(item=>item.inventoryType)
                this.categoryList = Array.from(new Set(this.categoryList))
                console.log(this.ruleForm.inventoryType);
                console.log(this.inventLists);
            })

            getspecscode(ele.breedName + "&materialType=中药饮片&ypCodeStandard="+(this.ruleForm.standard == undefined ? '':this.ruleForm.standard)).then((res)=>{
                this.codelist = res.data
            })
            this.getInvestmentList()
        },
        // 选择存货代码
        changeInvent(val){
            this.ruleForm.breedId = val.id
            this.ruleForm.loadingQuantity = val.loadingQuantity
            this.ruleForm.pelletWeight = val.pelletWeight
            this.ruleForm.inventoryCode = val.inventoryCode
            this.ruleForm.dispenserCode = val.dispenserCode
            this.ruleForm.ypQuantity = val.ypQuantity
            this.ruleForm.ypUnits = val.ypUnits
            this.deadLine = val.deadLine
        },

        // 选择负责人
        changePrincipa(ele){
            this.ruleForm.principalUserId = ele.id
            this.ruleForm.principalUser = ele.name
        },
        // 仓库管理
        changeWare(ele){
            this.ruleForm.warehouseId = ele.id
            this.ruleForm.warehouse = ele.name
        },
        remoteMethod1(query){

            findBreedNameBySearch({
                types: ['生产'],
                materialTypes: ['中药饮片'],
                searchName:query,
                standard:this.ruleForm.standard
            }).then((res) =>{
                this.productList = res.data
            })
        },
        // 投料
        changePin(val) {
            this.name = val
            this.isDisabled = false
            if(this.ruleForm.materialType == "中药饮片") {
                warehouse_findBatchByBreedName({
                    types: ['生产'],
                    materialTypes: ['中药饮片(半成品)'],
                    breedName: val,
                    standard:this.ruleForm.standard
                }).then((res) =>{
                    this.inBatchs = res.data
                })
                this.manufactureBatch = ''
            }
            this.init()
        },
        // 投料批号
        changeInBatch(val){
            this.ruleForm.productBatch = val.batch
            this.ruleForm.manufactureId = val.id

            this.ruleForm.time = val.time
            let data = this.name + "&inBatch=" + val.batch
            findQualityStandard(data).then((res)=>{
                this.ruleForm.qualityStandard = res.data[0].qualityStandard
            })
            this.scUseNum = val.surplusNum
            this.ruleForm.scUseNumUnits = val.units
        },
        // 投入量
        changeNum(){
            if(this.id == undefined){
                if (this.ruleForm.scUseNum <= 0) {
                    this.$notify.error({
                        title: '提示',
                        message: '数量不能为零或负数！',
                        showClose: false,
                        duration:3000
                    });
                    this.ruleForm.scUseNum = ''
                }
                if (this.ruleForm.scUseNum > this.scUseNum) {
                    this.$notify.error({
                        title: '提示',
                        message: '数量不能大于剩余量'+this.scUseNum+'！',
                        showClose: false,
                        duration:2000
                    });
                    this.ruleForm.scUseNum = ''
                }
            }else{
                if (this.ruleForm.scUseNum <= 0) {
                    this.$notify.error({
                        title: '提示',
                        message: '数量不能为零或负数！',
                        showClose: false,
                        duration:2000
                    });
                    this.ruleForm.scUseNum = this.newScUserNum
                }
                if (this.ruleForm.scUseNum > this.newScUserNum) {
                    this.$notify.error({
                        title: '提示',
                        message: '数量不能大于剩余量！',
                        showClose: false,
                        duration:2000
                    });
                    this.ruleForm.scUseNum = this.newScUserNum
                }
            }
        },
        // 跳转物料管理
        wuliaoLink(){
            var data = this.$store.getters.permission
            var items = ""
            for (let i = 0; i < data.length; i++) {
                if(data[i].name == "物料管理"){
                    items = 1
                }
            }
            if (items == "1"){
                this.$router.push({
                    path:'/materialsManagement/added'
                })
                if (this.ruleForm.materialType=='中药材') {
                    this.$store.commit('setStorge',this.ruleForm)
                } else if (this.ruleForm.materialType=='辅料') {
                    this.$store.commit('setStorge',this.ruleForm)
                } else if (this.ruleForm.materialType=='提取饮片') {
                    this.$store.commit('setStorge',this.ruleForm)
                } else if (this.ruleForm.materialType=='中药饮片') {
                    this.$store.commit('setStorge',this.ruleForm)
                }
            }else{
                this.$router.push({
                    path:'/403'
                })
            }

        },
        // 跳转单位管理
        unitLink(){
            var data = this.$store.getters.permission
            var items = ""
            for (let i = 0; i < data.length; i++) {
                if(data[i].name == "单位管理"){
                    items = 1
                }
            }
            if (items == "1"){
                this.$router.push({
                    path:'/unit',
                    query:{type:"added"}
                })
                if (this.ruleForm.materialType=='中药材') {
                    this.$store.commit('setStorge',this.ruleForm)
                } else if (this.ruleForm.materialType=='辅料') {
                    this.$store.commit('setStorge',this.ruleForm)
                } else if (this.ruleForm.materialType=='提取饮片') {
                    this.$store.commit('setStorge',this.ruleForm)
                } else if (this.ruleForm.materialType=='中药饮片') {
                    this.$store.commit('setStorge',this.ruleForm)
                }
            }else{
                this.$router.push({
                    path:'/403'
                })
            }

        },
        // 跳转仓库管理
        cangLink(){
            var _this = this
            var data = this.$store.getters.permission
            for (let i = 0; i < data.length; i++) {
                if(data[i].name == "库存管理"){
                    var items = data[i].children
                    setTimeout(function(){
                        for(var k=0;k<items.length;k++){
                            if(items[k].name=="仓库管理"){
                                this.items = 1
                            }
                        }
                    })
                }
            }
            setTimeout(function(){
                if(this.items == "1"){
                    _this.$router.push({
                        path:'/inventory/addInventory'
                    })
                    if (_this.ruleForm.materialType=='中药材') {
                        _this.$store.commit('setStorge',_this.ruleForm)
                    } else if (_this.ruleForm.materialType=='辅料') {
                        _this.$store.commit('setStorge',_this.ruleForm)
                    } else if (_this.ruleForm.materialType=='提取饮片') {
                        _this.$store.commit('setStorge',_this.ruleForm)
                    } else if (_this.ruleForm.materialType=='中药饮片') {
                        _this.$store.commit('setStorge',_this.ruleForm)
                    }
                }else{
                    _this.$router.push({
                        path:'/403'
                    })
                }
            },500)
        },
        // 跳转员工管理
        staffsLink(){
            var data = this.$store.getters.permission
            var items = ""
            for (let i = 0; i < data.length; i++) {
                if(data[i].name == "员工管理"){
                    items = 1
                }
            }
            if (items == "1"){
                this.$router.push({
                    path:'/staffsManagement/addedstaff'
                })
                if (this.ruleForm.materialType=='中药材') {
                    this.$store.commit('setStorge',this.ruleForm)
                } else if (this.ruleForm.materialType=='辅料') {
                    this.$store.commit('setStorge',this.ruleForm)
                } else if (this.ruleForm.materialType=='提取饮片') {
                    this.$store.commit('setStorge',this.ruleForm)
                } else if (this.ruleForm.materialType=='中药饮片') {
                    this.$store.commit('setStorge',this.ruleForm)
                }
            }else{
                this.$router.push({
                    path:'/403'
                })
            }
        },
        // 判断生产批号重复
        changeBatch(val) {
            pack_existBatch({batch:val}).then((res) =>{
                if (res.data == false) {
                    this.$notify.error({
                        title: '提示',
                        message: '批次号重复，请重新输入！',
                        showClose: false,
                        duration:2000
                    });
                    this.ruleForm.inBatch = "";
                }
            })
        },
        // 提交预览
        submitRules(formName){
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if (this.ruleForm.totalNumber != '') {
                        if(this.ruleForm.units == ''){
                            this.$notify.error({
                                title: '提示',
                                message: '产量单位必填！',
                                showClose: false,
                                duration:2000
                            });
                            return false;
                        }
                    }

                    // if(this.ruleForm.inventoryType == ''){
                    //     this.$notify.error({
                    //         title: '提示',
                    //         message: '产品大类必填！',
                    //         showClose: false,
                    //         duration:2000
                    //     });
                    //     return false;
                    // }
                    this.showForm = 2
                    // console.log(this.ruleForm)
                    // var date = new Date();
                    if(this.ruleForm.standard == 1){
                        this.standardl = "国标"
                    }else if(this.ruleForm.standard == 2){
                        this.standardl = "省标"
                    }else if(this.ruleForm.standard == 3){
                        this.standardl = "省标-北京"
                    }else if(this.ruleForm.standard == 4){
                        this.standardl = "省标-上海"
                    }
                    this.ruleForm.deadLine = this.deadLine
                } else {
                    return false;
                }
            })
        },
        submitForm() {
            console.log(this.ruleForm,112)
            if(this.id == undefined){
                this.ruleForm.materialType = '中药饮片'
                pack_save(this.ruleForm).then((res) => {
                    this.$notify({
                        title: '提示',
                        message: '保存成功',
                        type: 'success',
                        duration:1000
                    });
                    this.backPage()
                })
            } else{
                pack_update(this.ruleForm).then((res) => {
                    this.$notify({
                        title: '提示',
                        message: '修改成功',
                        type: 'success',
                        duration:1000
                    });
                    this.backPage()
                })
            }
        },
    }

}
</script>
<style lang="stylus" scoped>

</style>
